import {swipeCheck, getSwipeImg} from '@/api/login'
import {showNotify} from "vant";
import {defineStore} from "pinia";

const useSlideVerifyStore = defineStore('slideVerify', {
    state: () => ({
        // 组件名称 slider concat rotate
        componentName: "slider",
        // 提示
        tip: "拖动滑块完成拼图",
        // 滑动验证日志开关
        isPrintLog: false,
        // 图片数据
        captcha: {},
        //  图片数据id
        currentCaptchaId: "",
        // 滑动验证配置
        captchaConfig: {},
        // 用户拖动距离
        moveX: 0,
        // 是否验证成功
        verified: false,
        // 滑块按钮重置
        sliderBtnReset: true,
        // 滑块按钮按下
        DoDown: false,
        // 切割的小图片
        imgRest: false,
    }),
    geters: {
        // 组件名称 slider concat rotate
        getComponentName: (state) => state.componentName,
        // 提示
        getTip: (state) => state.tip,
        // 滑动验证日志开关
        getIsPrintLog: (state) => state.isPrintLog,
        // 图片数据
        getCaptcha: (state) => state.captcha,
        //  图片数据id
        getCurrentCaptchaId: (state) => state.currentCaptchaId,
        // 滑动验证配置
        getCaptchaConfig: (state) => state.captchaConfig,
        // 用户拖动距离
        getMoveX: (state) => state.moveX,
        // 是否验证成功
        getVerified: (state) => state.verified,
        // 滑块按钮重置
        getSliderBtnReset: (state) => state.sliderBtnReset,
        // 滑块按钮按下
        getDoDown: (state) => state.DoDown,
        // 切割的小图片
        getImgRest: (state) => state.imgRest,
    },
    actions: {
        // 重置
        reset() {
            this.sliderBtnReset = true;
            this.DoDown = false;
            this.imgRest = true;
            this.setMoveX(0);
            this.setVerified(false);
            this.setCurrentCaptchaId("");
            this.setCaptchaConfig({});
        },

        // 验证
        valid(captchaConfig) {
            let data = {
                bgImageWidth: captchaConfig.bgImageWidth,
                bgImageHeight: captchaConfig.bgImageHeight,
                sliderImageWidth: captchaConfig.sliderImageWidth,
                sliderImageHeight: captchaConfig.sliderImageHeight,
                startSlidingTime: captchaConfig.startTime,
                entSlidingTime: captchaConfig.stopTime,
                trackList: captchaConfig.trackArr
            };
            console.log("valid", captchaConfig, data);
            swipeCheck(this.currentCaptchaId, data).then((res) => {
                if (res) {
                    this.verified = true;
                    showNotify({type: 'success', message: ' 验证成功！'});
                } else {
                    this.verified = false;
                    showNotify({type: 'danger', message: ' 验证失败！'});
                    this.refreshCaptcha();
                }

            })
        },

        // 刷新
        refreshCaptcha(type) {
            return new Promise(resolve => {
                this.reset()
                // 向后端请求路由数据
                getSwipeImg(type || this.componentName).then(res => {
                    this.currentCaptchaId = res.id;
                    this.captcha = res.captcha;
                    resolve(res);
                })
            })
        },

        // 移动
        doMove(currentCaptchaConfig) {
            if (this.componentName == "Rotate") {
                this.moveX = (currentCaptchaConfig.moveX / (currentCaptchaConfig.end / 360));
            } else {
                this.moveX = currentCaptchaConfig.moveX;
            }
        },

        clearPreventDefault(event) {
            if (event.preventDefault) {
                event.preventDefault();
            }
        },

        clearAllPreventDefault($div) {
            for (let i = 0; i < $div.length; i++) {
                $div[i].addEventListener('touchmove', this.clearPreventDefault, false);
            }
        },

        reductionAllPreventDefault($div) {
            for (let i = 0; i < $div.length; i++) {
                $div[i].addEventListener('touchmove', this.clearPreventDefault);
            }
        },

        /**
         * 打印日志
         * @param params
         */
        printLog(...params) {
            if (this.isPrintLog) {
                console.log(JSON.stringify(params));
            }
        },

        /**
         * 初始化配置项
         * @param bgImageWidth
         * @param bgImageHeight
         * @param sliderImageWidth
         * @param sliderImageHeight
         * @param end
         * @returns {*|{bgImageWidth, sliderImageWidth, bgImageHeight, startTime: Date, end, sliderImageHeight, trackArr: *[], movePercent: number}}
         */
        initConfig(bgImageWidth, bgImageHeight, sliderImageWidth, sliderImageHeight, end) {
            this.captchaConfig = {
                startTime: new Date(),
                trackArr: [],
                movePercent: 0,
                bgImageWidth,
                bgImageHeight,
                sliderImageWidth,
                sliderImageHeight,
                end
            }
            this.printLog("init", this.captchaConfig);
            return this.captchaConfig;
        },

        /**
         * 开始点击
         * @param event
         */
        down(event) {
            return new Promise(resolve => {
                let targetTouches = event.originalEvent ? event.originalEvent.targetTouches : event.targetTouches;
                let startX = event.pageX;
                let startY = event.pageY;
                if (startX === undefined) {
                    startX = Math.round(targetTouches[0].pageX);
                    startY = Math.round(targetTouches[0].pageY);
                }
                this.captchaConfig.startX = startX;
                this.captchaConfig.startY = startY;
                const pageX = this.captchaConfig.startX;
                const pageY = this.captchaConfig.startY;
                const startTime = this.captchaConfig.startTime;
                const trackArr = this.captchaConfig.trackArr;
                trackArr.push({
                    x: pageX - startX,
                    y: pageY - startY,
                    type: "down",
                    t: (new Date().getTime() - startTime.getTime())
                });
                this.printLog("start", startX, startY)
                // pc
                window.addEventListener("mousemove", this.move);
                window.addEventListener("mouseup", this.up);
                // 手机端
                window.addEventListener("touchmove", this.move, false);
                window.addEventListener("touchend", this.up, false);
                this.sliderBtnReset = false;
                this.DoDown = true;
                resolve();
            })

        },

        /**
         * 移动
         * @param event
         * @param name
         * @returns {number}
         */
        move(event) {
            if (event instanceof TouchEvent) {
                event = event.touches[0];
            }
            let pageX = Math.round(event.pageX);
            let pageY = Math.round(event.pageY);
            const startX = this.captchaConfig.startX;
            const startY = this.captchaConfig.startY;
            const startTime = this.captchaConfig.startTime;
            const end = this.captchaConfig.end;
            const bgImageWidth = this.captchaConfig.bgImageWidth;
            const trackArr = this.captchaConfig.trackArr;
            let moveX = pageX - startX;
            const track = {
                x: pageX - startX,
                y: pageY - startY,
                type: "move",
                t: (new Date().getTime() - startTime.getTime())
            };
            trackArr.push(track);
            if (moveX < 0) {
                moveX = 0;
            } else if (moveX > end) {
                moveX = end;
            }
            this.captchaConfig.moveX = moveX;
            this.captchaConfig.movePercent = moveX / bgImageWidth;
            this.doMove(this.captchaConfig)
            this.printLog("move", track);
        },

        /**
         * 松开
         * @param event
         */
        up(event) {
            window.removeEventListener("mousemove", this.move);
            window.removeEventListener("mouseup", this.up);
            window.removeEventListener("touchmove", this.move);
            window.removeEventListener("touchend", this.up);
            if (event instanceof TouchEvent) {
                event = event.changedTouches[0];
            }
            this.captchaConfig.stopTime = new Date();
            let pageX = Math.round(event.pageX);
            let pageY = Math.round(event.pageY);
            const startX = this.captchaConfig.startX;
            const startY = this.captchaConfig.startY;
            const startTime = this.captchaConfig.startTime;
            const trackArr = this.captchaConfig.trackArr;

            const track = {
                x: pageX - startX,
                y: pageY - startY,
                type: "up",
                t: (new Date().getTime() - startTime.getTime())
            }

            trackArr.push(track);
            this.printLog("up", track)
            this.valid(this.captchaConfig);
        },

        setMoveX(x) {
            this.moveX = x;
        },
        setComponentName(name) {
            this.componentName = name;
        },
        setVerified(val) {
            this.verified = val;
        },
        setCurrentCaptchaId(id) {
            this.currentCaptchaId = id;
        },
        setCaptchaConfig(data) {
            this.captchaConfig = data;
        },
    }
})

export default useSlideVerifyStore
